<%@ page language="java" contentType="text/html; charset=GBK"%>
<%@ page import="java.lang.Runnable"%>
<%@ page import="java.lang.Thread"%>
<%@ page import="java.io.*"%>
<%@ page import="edu.zju.PortFinder"%>
<%@ page import="java.util.Map"%>
<%@ page import="edu.zju.BurnRunnable"%>
<%@ page import="java.util.concurrent.CountDownLatch" %>
<%
	String realPath = application.getRealPath("/");
	String uploadPath = realPath + "upload"; //FIXME:the last / of realPath

	String success = "Success!";
	String warning = "Error!\nCannot connect to Nodes!";
	request.setCharacterEncoding("GBK");
	String nodestr = request.getParameter("showid");
	String[] strarray = nodestr.split(",");
	String cmd = "";
	Cookie[] cookies = request.getCookies();
	

	System.out.println(nodestr);

	//About State
	StringBuilder infoMsg = new StringBuilder();
	StringBuilder errorMsg = new StringBuilder();
	String line = null;

	PortFinder finder = new PortFinder(realPath);
	Map<String, String> usbNumMap = finder.find(); //id => port (id from 1 ~ 36)
	System.out.println("burn.jsp:" + usbNumMap + "\n" + realPath + "\n" + uploadPath + "\n" + strarray.length + "\n");
	String filename = "";

	for (int i = 0; i < cookies.length; i++) {
		if (cookies[i].getName().equals("filename")) {
			filename = cookies[i].getValue();
		}
	}
	
	CountDownLatch latch = new CountDownLatch(strarray.length);
	
	for (int i = 0; i < strarray.length; i++)//zhe li yong string de length
	{
		int nodeid = Integer.parseInt(strarray[i]); //NOTE: we tag the nodes from 1 ~ 36
		System.out.println("burn.jsp: nodeid " + nodeid);
		String port = usbNumMap.get("" + nodeid);
		if ( port != null && port != ""){
			int usbnumber = Integer.parseInt(port);
			System.out.println("burn: " + nodeid + "," + usbnumber);
			Thread t = new Thread(new BurnRunnable(nodeid, usbnumber, uploadPath + "/" + filename,latch));
			t.start();
		}else{
			BurnRunnable.usbandvalue += nodeid + "," + 1 + ",";
			latch.countDown();
		}
	}
	
	latch.await();
	//while (BurnRunnable.index < (strarray.length)) {
	//	boolean flag = true;
	//	if (flag) {
	//		out.println("");
	//		flag = false;
	//	}
	//}
	out.println(BurnRunnable.usbandvalue);
	BurnRunnable.end();
%>